package cn.hxsteel.storage.core.filter;

import java.net.URL;
import java.util.Enumeration;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.constructs.blocking.LockTimeoutException;
import net.sf.ehcache.constructs.web.AlreadyCommittedException;
import net.sf.ehcache.constructs.web.AlreadyGzippedException;
import net.sf.ehcache.constructs.web.filter.FilterNonReentrantException;
import net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter;
import net.sf.ehcache.util.ClassLoaderUtil;

/**
 * 页面EH缓存过滤器
 */
// @formatter:off
public class PageEHCacheFilter extends SimplePageCachingFilter
{
    /**
     * 符合页面EH缓存的资源地址数组
     */
    // @formatter:off
    private static String[] PAGE_EHCACHE_URI_ARRAY = new String[] {
	"/sumTotalDepot",
	"/sumDayDepot"
    };
    
    @Override
    protected void doFilter( final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain )
	    throws AlreadyGzippedException, AlreadyCommittedException, FilterNonReentrantException, LockTimeoutException, Exception
    {	
	boolean usePageEHCache = false;
	String uri = request.getRequestURI();
	for ( String cacheURI : PAGE_EHCACHE_URI_ARRAY )
	{
	    if ( uri.contains( cacheURI ) )
	    {
		usePageEHCache = true;
		break;
	    }
	 }
	
	// 如果包含我们要缓存的uri 就缓存该页面，否则执行正常的页面转向
	if ( usePageEHCache )
	{
	    super.doFilter( request, response, chain );
	}
	else
	{
	    chain.doFilter( request, response );
	}
    }
    
    /**
     * 获取缓存名称
     */
    @Override
    protected String getCacheName()
    {
        return "page";
    }

    /**
     * 获取缓存管理器
     */
    @Override
    protected CacheManager getCacheManager()
    {
	ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
	URL url = standardClassloader.getResource("/ehcache-page.xml");
        return CacheManager.create( url );
    }
   
    /**
     * 兼容ie6/7 gzip压缩
     */
    @Override
    protected boolean acceptsGzipEncoding( HttpServletRequest request )
    {
	boolean ie6 = _headerContains( request, "User-Agent", "MSIE 6.0" );
	boolean ie7 = _headerContains( request, "User-Agent", "MSIE 7.0" );
	return acceptsEncoding( request, "gzip" ) || ie6 || ie7;
    }
    
    /**
     * 判断浏览器版本
     */
    private boolean _headerContains( final HttpServletRequest request, final String header, final String value )
    {
	logRequestHeaders( request );
	@SuppressWarnings( "rawtypes" )
	final Enumeration accepted = request.getHeaders( header );
	while ( accepted.hasMoreElements() )
	{
	    final String headerValue = (String) accepted.nextElement();
	    if ( headerValue.indexOf( value ) != -1 ) { return true; }
	}
	return false;
    }
}